//
//  ClientManager.m
//  Client
//
//  Created by jyh on 2018/7/25.
//  Copyright © 2018年 huig. All rights reserved.
//

#import "ClientManager.h"
#import "GCDAsyncSocket.h"
#import "MessageCompile.h"
@interface ClientManager()<GCDAsyncSocketDelegate>

@property (strong, nonatomic) GCDAsyncSocket *clientSocket;
// 连接状态
@property (nonatomic, assign) BOOL connected;
// 定时器线程
@property (nonatomic, strong) NSThread *thread;
@end

@implementation ClientManager

#pragma mark -- 外部接口
// 连接服务器
- (BOOL)connectServerAddress:(NSString *)address post:(NSInteger)post {
    NSError *error = nil;
    if (self.connected) return YES;
    
    self.connected = [self.clientSocket connectToHost:address onPort:post error:&error];
    if (error || !self.connected) return NO;
    
    if (self.connected) {
        [self.thread start];
    }
    return self.connected;
}

// 发送信息
- (void)sendMessage:(NSData *)data {
    [self.clientSocket writeData:data withTimeout:-1 tag:0];
}

#pragma mark -- GCDAsyncSocketDelegate

/**
 连接主机对应端口号
 
 @param sock 客户端socket
 @param host 主机
 @param port 端口号
 */
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {

    [self sendSystemMessage:[NSString stringWithFormat:@"连接成功,服务器IP:%@:%d", host,port]];
    
    // 连接后,可读取服务器端的数据
    [self.clientSocket readDataWithTimeout:- 1 tag:0];
    self.connected = YES;
}

/**
 读取数据
 
 @param sock 客户端socket
 @param data 读取到的数据
 @param tag 当前读取的标记
 */
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {

    if ([self.delegate respondsToSelector:@selector(clientManager:data:)]) {
        [self.delegate clientManager:self data:data];
    }
    // 读取到服务器数据值后,能再次读取
    [self.clientSocket readDataWithTimeout:- 1 tag:0];
}

/**
 客户端socket断开
 
 @param sock 客户端socket
 @param err 错误描述
 */
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    [self sendSystemMessage:@"断开连接"];
    self.clientSocket.delegate = nil;
    self.clientSocket = nil;
    self.connected = NO;
    [self.clientSocket disconnect];
    self.thread = nil;
}

#pragma mark -- 内部方法

- (void)sendSystemMessage:(NSString *)message {
    NSData *data = [MessageCompile packageMessage:message messageType:(messageTypeSystem) packageType:(packageTypeString)];
    if ([self.delegate respondsToSelector:@selector(clientManager:data:)]) {
        [self.delegate clientManager:self data:data];
    }
}


static ClientManager *_shareInstance;
+ (instancetype)shareInstance {
    if (!_shareInstance) {
        _shareInstance = [[self alloc] init];
    }
    return _shareInstance;
}

// 添加计时器
- (void)addTimer
{
    // 长连接定时器
    [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];
    // 把定时器添加到当前运行循环,并且调为通用模式
    [[NSRunLoop currentRunLoop] run];
}

// 心跳连接
- (void)longConnectToSocket
{
    // 发送固定格式的数据,指令@"longConnect"
    float version = [[UIDevice currentDevice] systemVersion].floatValue;
    NSString *longConnect = [NSString stringWithFormat:@"%f",version];
    NSData  *data = [MessageCompile packageMessage:longConnect messageType:(messageTypeHeart) packageType:(packageTypeString)];
    
    [self.clientSocket writeData:data withTimeout:-1 tag:0];
}

- (NSThread *)thread {
    if (!_thread) {
        _thread = [[NSThread alloc] initWithTarget:self selector:@selector(addTimer) object:nil];
    }
    return _thread;
}

- (GCDAsyncSocket *)clientSocket {
    if (!_clientSocket) {
        _clientSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    }
    return _clientSocket;
}

@end
